/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.se2.meteocal.control;

import it.polimi.se2.meteocal.entity.Calendar;
import it.polimi.se2.meteocal.entity.Group;
import it.polimi.se2.meteocal.entity.Users;
import java.security.Principal;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Ugo
 */
@Stateless
public class UserManager {

    @PersistenceContext
    public EntityManager em;
    
    @Inject
    Principal principal;
    
    public void save(Users user) {
        user.setGroupname(Group.USERS); 
        em.persist(user);
        Calendar newCalendar = new Calendar(user);
        em.persist(newCalendar);
    }
     
    public void edit(Users user){
        em.merge(user);
    }

    public void unregister() {
        em.remove(getLoggedUser());
    }

    public Users getLoggedUser() {
        return em.find(Users.class, principal.getName());
    }
    
    public List<Users> findOtherUsers() {
        List<Users> allUser = em.createNamedQuery(Users.findAll, Users.class)
                .getResultList();
       
        for(Users u: allUser)
            if(u.getEmail().equals(getLoggedUser().getEmail())){
                allUser.remove(u);
                break;
            }
        return allUser;
    }
    
    public Users findUserByEmail(String email){
        return em.createNamedQuery(Users.findByEmail, Users.class)
                .setParameter("email",email)
                .getSingleResult();
    }
}
